package com.resign.carl.observer.api.impl;

import com.google.common.collect.Lists;
import com.resign.carl.observer.api.Observer;
import com.resign.carl.observer.api.Subject;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;

/**
 * Created by carl.zhao on 2016/6/13.
 */
public class WeatherData implements Subject {
    private List<Observer> observers = Lists.newArrayList();
    // 温度
    private float temp;
    // 温度
    private float humidity;
    // 气压
    private float pressure;

    @Override
    public void registerObserver(Observer o) {
        if(o == null){
            throw new NullPointerException();
        }
        observers.add(o);
    }

    @Override
    public void removeObserver(Observer o) {
        if(o == null){
            throw new NullPointerException();
        }
        int index = observers.indexOf(o);
        if(index > 0){
            observers.remove(o);
        }
    }

    @Override
    public void notifyObservers() {
        if(CollectionUtils.isEmpty(observers)){
            return;
        }
        for(Observer observer : observers){
            observer.update(temp, humidity, pressure);
        }
    }

    public void measurementsChanged(){
        notifyObservers();
    }

    public void setMeasurements(float temperature, float humidity, float pressure) {
        this.temp = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }
}
